from mySocket import *
from aliyun import *
import json
import traceback
from MYSQL import MYSQL
import threading

g_conn_pool = []  # 连接池


def message_handle(tcpCliSock):
    """
    消息处理
    """
    while True:
        com, dataSize, guid, data = c_socket.socketReceive(tcpCliSock)

        if com == 0:  # 注册设备
            data = str(data, encoding="utf8")
            data = json.loads(data)
            device = mysql.selestMACbyAll(data['MAC'])
            if len(device) == 0:
                print(mysql.insertDevice(data['MAC'], data['location']))
                c_socket.socketSend(tcpCliSock, b'OK', 0)
            else:
                c_socket.socketSend(tcpCliSock, b'exist', 1)

        elif com == 1:  # 添加人脸
            flag = 0
            data = str(data, encoding="utf8")
            data = json.loads(data)
            for Entities in Sample.ListFaceEntities("lunwen"):
                if Entities['EntityId'] == data['entity_id']:
                    print('添加失败：' + data['entity_id'] + '存在')
                    c_socket.socketSend(tcpCliSock, b'exist ID', 1)
                    flag = 1
                    break
            if flag == 0:
                studentName = mysql.selestIDbyName(data['entity_id'])
                if Sample.AddDeleteFace_Entity(db_name='lunwen', entity_id=data['entity_id'],
                                               entity_operate=operate.Create) == 200:
                    print('添加数据成功')
                    c_socket.socketSend(tcpCliSock, ''.join(studentName).encode(), 0)

                    for i in range(3):
                        flag = 0
                        while flag == 0:
                            with open('messigray.png', 'wb') as image:
                                image.write(c_socket.socketReceive(tcpCliSock)[3])
                            ru = str(Sample.AddFace("lunwen", 'messigray.png', data['entity_id']))
                            if ru != 400:
                                flag = 1
                                sdata = {"msg": "第" + str(i + 1) + "张"}
                                c_socket.socketSend(tcpCliSock, bytes(json.dumps(sdata).encode('utf-8')), 0)
                            else:
                                sdata = {"msg": "拍摄失败请重试"}
                                c_socket.socketSend(tcpCliSock, bytes(json.dumps(sdata).encode('utf-8')), 2)
                            print(flag)
                        print(i)
                    c_socket.socketSend(tcpCliSock, ''.join(studentName).encode() + b' OK', 3)
                    c_socket.socketSend(tcpCliSock, ''.join(studentName).encode() + b' OK', 0)
                else:
                    c_socket.socketSend(tcpCliSock, ''.join(studentName).encode() + b' error', 1)

        elif com == 2:  # 查找登记人脸
            with open('messigray.png', 'wb') as image:
                image.write(data)
            faceList = Sample.SearchFace(db_name='lunwen', image_path='messigray.png')
            # print(len(faceList))
            if len(faceList) == 0:
                c_socket.socketSend(tcpCliSock, b'not found', 1)
                continue
            elif faceList == "input image not found face":
                c_socket.socketSend(tcpCliSock, bytes(json.dumps(faceList).encode('utf-8')), 1)
                continue
            else:
                student_id = faceList[0]['EntityId']
                face_name = mysql.selestIDbyName(student_id)
                if face_name == "input image not found face":
                    result = face_name
                else:
                    result = mysql.insertCheckIn(student_id, 23)
                data = {"result": result, "face_name": face_name}
                c_socket.socketSend(tcpCliSock, bytes(json.dumps(data).encode('utf-8')), 0)


def accept_client():
    """
        接收新连接
        """
    while True:
        tcpCliSock, addr = c_socket.tcpSerSock.accept()  # 阻塞，等待客户端连接
        # 加入连接池
        g_conn_pool.append(tcpCliSock)
        # 给每个客户端创建一个独立的线程进行管理
        accept_thread = threading.Thread(target=message_handle, args=(tcpCliSock,))
        # 设置成守护线程
        accept_thread.daemon = True
        accept_thread.start()


if __name__ == "__main__":

    c_socket = mySocket(getConfig("client.config", 'socket', 'host'), int(getConfig("client.config", 'socket', 'port')))
    mysql = MYSQL()
    while True:
        a = 0
        try:
            thread = threading.Thread(target=accept_client)
            thread.daemon = True
            thread.start()
            while True:
                pass
        except Exception as e:
            print(e)
            traceback.print_exc()  # 输出详细的异常信息
